﻿/// <reference path="worm.js" />
/// <reference path="application.js" />
/// <reference path="controller.js" />
/// <reference path="inputManager.js" />
/// <reference path="debugInfo.js" />
/// <reference path="scene.js" />

// [Temp] Test collision point!
/// <reference path="collisionPoint.js" />
/// <reference path="collisionPointSolid.js" />
var collisionPointTest = new CollisionPoint(500, 900);
var collvy = 0;

/// Main loop
window.app.action.Step = function () {
    // Clear the surface canvas
    window.app.context.container2d.clearRect(0, 0, window.app.context.container.width, window.app.context.container.height);

    // Make the controller think
//    if (window.app.context.activeController != null) {
//        window.app.context.activeController.Think();
//    }

    // Make the controllers think
    for (index in app.data.controllers) {
        window.app.data.controllers[index].Think();
    }

    if (window.app.context.isInDebugMode) {
        DrawDebugInfo();
    }

    // Draw world
    window.app.data.scene.Draw();

    // Loop through each worm
    for (index in app.data.worms) {
        window.app.data.worms[index].Think();
        window.app.data.worms[index].Draw();
    }

    // [Temp] Test collision point!
    collisionPointTest.Move(0, collvy);
    collvy = this.collisionPointTest.isInCollision ? collvy * -0.5 : collvy + app.context.gravity / app.context.frameRate;
    collisionPointTest.Draw();

    // Make the camera business
    window.app.data.camera.Think();
};

/// Starts the game loop when application is ready
window.app.action.StartLoopIfReady = function () {
    if(app.context.sceneIsLoaded) {
        app.input.inputManager.Start();
        window.setInterval(app.action.Step, 1000 / app.context.frameRate);
    }
};

/// Occurs when the window as been loaded
window.onload = function () {

    // Context initialization
    app.context.container = document.getElementById("container");
    app.context.container2d = app.context.container.getContext("2d");

    // Scene initialization
    window.app.data.scene.onload = function () { window.app.context.sceneIsLoaded = true; window.app.action.StartLoopIfReady(); };
    window.app.data.scene.Initialize();

    var worm = new Worm();
    var controller = new Controller(worm);
    controller.isActive = true;

    app.data.worms.push(worm);
    app.data.controllers.push(controller);

    //app.context.activeController = controller;
    app.context.activeWorm = worm;
};